<?php
namespace app\common\repositories\delivery;

use app\common\dao\delivery\DeliveryExpressOrderDao;
use app\common\model\delivery\DeliveryExpressOrder;
use app\common\model\delivery\DeliveryStation;
use app\common\model\store\order\StoreOrder;
use app\common\model\system\merchant\Merchant;
use app\common\repositories\BaseRepository;
use app\common\repositories\store\order\StoreOrderRepository;
use app\common\repositories\store\order\StoreOrderStatusRepository;
use app\common\repositories\system\merchant\MerchantRepository;
use app\common\repositories\system\serve\ServeOrderRepository;
use app\common\repositories\user\UserRepository;
use crmeb\services\DeliveryExpressSevices;
use crmeb\services\DeliverySevices;
use FormBuilder\Factory\Elm;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;
use think\facade\Route;

class DeliveryExpressOrderRepository extends BaseRepository
{

    public function __construct(DeliveryExpressOrderDao $dao)
    {
        $this->dao = $dao;
    }

    public function merList(array $where, int $page, int $limit)
    {
        $query = $this->dao->getSearch($where)->with(['station','storeOrder'])->order('create_time DESC');
        $count = $query->count();
        $list = $query->page($page, $limit)->select();

        return compact('count', 'list');
    }

    public function sysList(array $where, int $page, int $limit)
    {
        $query = $this->dao->getSearch($where)->with([
            'merchant' => function($query) {
                $query->field('mer_id,mer_name');
            },
            'station',
            'storeOrder'=> function($query) {
                $query->field('order_id,order_sn');
            },
        ])->order('create_time DESC');
        $count = $query->count();
        $list = $query->page($page, $limit)->select();

        return compact('count', 'list');
    }

    public function cancelForm($id)
    {
        $formData = $this->dao->get($id);
        if (!$formData) throw new ValidateException('订单不存在');
        if ($formData['status'] == -1) throw new ValidateException('订单已取消，无法操作');

        $form = Elm::createForm(Route::buildUrl('merchantStoreDeliveryExpressOrderCancel',['id' => $id])->build());
        $rule = [];
        $rule[] =  Elm::text('cancel_reason', '取消原因');;
        $form->setRule($rule);
        return $form->setTitle('取消快递配送订单',$formData);
    }

    public function cancel($id, $merId, $reason)
    {
        $order = $this->dao->getWhere([$this->dao->getPk() => $id, 'mer_id' => $merId]);
        if (!$order) throw new ValidateException('订单不存在');
        if ($order['status'] == -1) throw new ValidateException('请勿重复操作');
        $data = [
            'origin_id' => $order['platform_order_sn'],
            'order_code'=> $order['order_code'],
            'reason'    => $reason['reason'],
            'cancel_reason' => $reason['cancel_reason'],
        ];
        return Db::transaction(function () use($order, $data){
            $mark = $data['reason'];
            if ($data['cancel_reason']) $mark .= ','.$data['cancel_reason'];
            $res = DeliveryExpressSevices::create($order['delivery_code'])->cancelOrder($data);
            $deduct_fee = 0;
            $this->cancelAfter($order, $deduct_fee, $mark);
            //订单记录
            $statusRepository = app()->make(StoreOrderStatusRepository::class);
            $orderStatus = [
                'order_id' => $order->order_id,
                'order_sn' => $order->order_sn,
                'type' => $statusRepository::TYPE_ORDER,
                'change_message' => '快递配送订单已取消',
                'change_type' => $statusRepository::ORDER_DELIVERY_CITY_CANCEL,
            ];
            $statusRepository->createAdminLog($orderStatus);
        });
    }

    public function cancelAfter($deliveryOrder, $deductFee, $mark)
    {
        //修改配送订单
        $deliveryOrder->status = -1;
        $deliveryOrder->reason = $mark;
        $deliveryOrder->deduct_fee = $deductFee;
        $deliveryOrder->save();

        //修改商城订单
        $res = app()->make(StoreOrderRepository::class)->get($deliveryOrder['order_id']);
        $res->status = 0;
        $res->delivery_type = 0;
        $res->delivery_name = '';
        $res->delivery_id = '';
        $res->save();

        //修改商户
        $merchant = app()->make(MerchantRepository::class)->get($deliveryOrder['mer_id']);
        $balance = bcadd(bcsub($deliveryOrder['fee'], $deductFee, 2), $merchant->delivery_balance, 2);
        $merchant->delivery_balance = $balance;
        $merchant->save();
    }


    public function updateDelivery($data,$order)
    {
        return Db::transaction(function () use ($data, $order) {
            $merechant = (new Merchant())->where('mer_id',$order['mer_id'])->find();
            $merechant->delivery_balance = bcsub($merechant->delivery_balance, $data['fee'], 2);
            $merechant->save();

            $model =  (new DeliveryExpressOrder())->where(['order_id'=>$order['order_id'],'status'=>2])->order('delivery_express_order_id desc')->find();
            $model->fee =$data['fee'];
            $model->delivery_product_name = $data['delivery_product_name'];
            $model->return_msg = $data['return_msg'];
            $model->status = $data['status'];
            $model->save();
        });

        return true;

    }


    public function show(int $id, int $uid)
    {
        $where['order_id'] = $id;
        $where['uid'] = $uid;
        $res = $this->dao->getSearch($where)->with(['storeOrderStatus','storeOrder'])->find();
        if (!$res) throw new ValidateException('订单不存在');
        return $res;
    }


}
